package com.zxr.demo.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxr.demo.application.QiniuAiConfig;
import com.zxr.demo.commom.bo.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QiniuAiService {

    @Autowired
    private QiniuAiConfig qiniuAiConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 调用七牛云AI接口获取回复
     */
    public String getAiResponse(List<ChatMessage> historyMessages) {
        try {
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + qiniuAiConfig.getApiKey());

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("stream", false);
            requestBody.put("model", qiniuAiConfig.getModel());

            // 转换历史消息格式
            List<Map<String, String>> messages = new ArrayList<>();
            // 添加系统提示
            Map<String, String> systemMsg = new HashMap<>();
            systemMsg.put("role", "system");
            systemMsg.put("content", "你有一个有用的助手");
            messages.add(systemMsg);

            // 添加历史对话
            for (ChatMessage msg : historyMessages) {
                Map<String, String> message = new HashMap<>();
                message.put("role", msg.getMessageType() == 1 ? "user" : "assistant");
                message.put("content", msg.getContent());
                messages.add(message);
            }
            requestBody.put("messages", messages);

            // 发送请求
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(
                    qiniuAiConfig.getApiUrl(),
                    request,
                    String.class
            );

            // 解析响应
            if (response.getStatusCode().is2xxSuccessful()) {
                JsonNode jsonNode = objectMapper.readTree(response.getBody());
                return jsonNode.get("choices").get(0).get("message").get("content").asText();
            } else {
                throw new RuntimeException("七牛云AI接口调用失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("获取AI回复失败", e);
        }
    }
}
